//
//  ContentView.swift
//  WatchShouChong Watch App
//
//  Created by yw on 2024/8/16.
//

import SwiftUI
import WatchConnectivity
import HealthKit

struct ContentView: View {
    let seesion = WCSession.default
    @ObservedObject var watchVM:WatchViewModel = WatchViewModel()
    
    @State var count:Int = 0
    @State var isStart:Bool = true
    @State var healthStore:HKHealthStore?
    @State var heartCount:Double = 0.0
    @State var heartTimer:Timer?
    
    @State private var totalSeconds = 0.0
    // 状态变量，控制计时器是否运行
    @State private var isTimerRunning = false
    // 计时器的引用，用于暂停和恢复
    @State private var timer: Timer?
//    @Binding var isStart:Bool
    let timerInterval:Double = 1.0 // 计时器的间隔时间，单位为秒
    
    @Environment(\.dismiss) var dismiss
    @State private var showAlert:Bool = false
    @State private var showSheet:Bool = false
    var body: some View {
        TabView {
            if !showSheet {
                VStack {
                    HStack {
                        countView
                        Spacer()
                    }
                    heartView
                    VStack {
                        HStack {
                            Image(systemName: "clock.fill")
                                .foregroundColor(Color("color_blue"))
                            Text(formatTime())
                                .lineLimit(0)
                                .font(Font.system(size: 40, weight: .bold, design: .rounded))
                                .foregroundColor(Color("color_blue"))
                            
                            Spacer()
                        }
                        
                    }
                    
                }
                VStack {
                    
                    Button(action: {
                        startAction()
                    }, label: {
                        HStack {
                            Image(systemName: !isStart ? "play.fill" : "pause.fill")
                            Text(!isStart ? "继续":"暂停")
                        }
                        
                    })
                    Button(action: {
                        resetTimer()
                    }, label: {
                        HStack {
                            Image(systemName: "stop.fill")
                            Text("结束")
                        }
                    })
                    
                    
                }
            }
        }.tabViewStyle(.carousel)
            .alert("提示", isPresented: $showAlert, actions: {
                Button(role: .cancel) {
                    
                } label: {
                    Text("确定")
                }

            }, message: {
                Text("数据同步到iPhone失败，请稍后再试")
            })
        
        .onAppear {
            startCountAction()
            startTimer()
            getHealthPremission()
        }
        .onDisappear{
            count = 0
            GyroMannager.shared.resetCount()
            self.heartTimer?.invalidate()
            self.heartTimer = nil
            self.timer?.invalidate()
            self.timer = nil
        }.overlay(alignment: .center) {
            if self.showSheet {
                SendMsgView { remark in
                    let sendData:[String:String] = [
                        "count":String(count),
                        "heartRate":String(Int(heartCount)),
                        "time":String(Int(totalSeconds)),
                        "isWatch":"1",
                        "remark":remark
                    ]
                    watchVM.sendMsg(sendData: sendData) { flag in
                        if !flag {
                            showAlert.toggle()
                        } else {
                            DispatchQueue.main.async {
                                self.dismiss()
                            }
                        }
                    }
                }
            }
           
        }

    }
    
    
    var countView:some View {
        HStack {
            Text("\(count)")
                .lineLimit(0)
                .font(Font.system(size: 50, weight: .bold, design: .rounded))
                .foregroundColor(Color("color_orange"))
            Spacer()
        }
    }
    
    private func startAction() {
        isStart.toggle()
        if isStart {
            startTimer()
        } else {
            pauseTimer()
        }
    }
    
    private func startTimer() {
        startCountAction()
        DispatchQueue.main.async {
            self.timer = Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true) { _ in
                totalSeconds += timerInterval
            }
        }
        
    }
    
    private func pauseTimer() {
        
        timer?.invalidate()
        timer = nil
        GyroMannager.shared.stop()
    }
    
    private func resetTimer() {
        pauseTimer()
        withAnimation {
            showSheet.toggle()
        }
    }
    
    private func startCountAction() {
        GyroMannager.shared.start(isPuase: !isStart) { speed in
            
        } countBlock: { count in
            
            self.count = count
        }
    }
    
    // 格式化时间显示为mm:ss
    private func formatTime() -> String {
        let minutes = Int(totalSeconds) / 60
        let seconds = Int(totalSeconds) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
    
    
    var heartView:some View {
        HStack {
            Image(systemName: "heart.fill")
                .foregroundColor(Color("color_red"))
            HStack(alignment: .bottom) {
                Text("\(String(format: "%.1f", heartCount))")
                    .lineLimit(0)
                    .font(Font.system(size: 40, weight: .bold, design: .rounded))
                    .foregroundColor(Color("color_red"))
                Text("次/分")
                    .font(Font.system(size: 20, weight: .bold, design: .rounded))
                    .foregroundColor(Color("color_red"))
            }
            
            
            Spacer()
        }
    }
    
    private func getHealthPremission() {
        self.healthStore = .init()
        let shares:Set<HKSampleType> = Set([
            HKSampleType.quantityType(forIdentifier: .heartRate)!
        ])
        let reads = Set([
            HKObjectType.quantityType(forIdentifier: .heartRate)!
        ])
        self.healthStore!.requestAuthorization(toShare: shares, read: reads) { flag, error in
            if !flag {
                print("没有权限")
                return
            }
            print("有权限")
//            getUserHeartRate()
            startHeartTimer()
//            startTimer()     
        }
        
    }
    
    private func startHeartTimer() {
        DispatchQueue.main.async {
            self.heartTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true, block: { _ in
                getUserHeartRate()
            })
            
        }
    }
    
    private func getUserHeartRate() {
        let query =  HKSampleQuery(sampleType: HKSampleType.quantityType(forIdentifier: .heartRate)!,predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { qu, results, error in
            if error != nil {
                print("报错了")
            } else {
                if let res = results?.last as? HKQuantitySample {
                    let heart = res.quantity.doubleValue(for:HKUnit(from: "count/min"))
                    print("心跳\(heart)")
                    self.heartCount = heart
                }
            }
        }
        self.healthStore?.execute(query)
    }
}

